package com.demon.framework.util.request;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Demon-HY
 * @date 2020/5/22
 */
public class RequestContextUtil {

    public static HttpServletRequest request() {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return requestAttributes == null ? null : requestAttributes.getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    public static HttpServletResponse response() {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            return requestAttributes == null ? null : requestAttributes.getResponse();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 生成RequestId
     */
    public static String genRequestId(){
        long nanoTime = System.nanoTime();
        String nanoTime100= nanoTime +""+ RandomUtils.nextInt(0,1000);
        nanoTime100=nanoTime100.substring(4);
        return Long.toString(Long.parseLong(nanoTime100),Character.MAX_RADIX);
    }
}

